package udpserver

import (
	"context"
	"fmt"
	"nprobe/core"
)

func NewUDPServerReceiverGroup(
	ctx context.Context, name string, task *core.ProbeTask, maxPPSPerReceiver int, salts map[int][]byte,
) *core.ReceiverGroup {
	var receivers []core.Receiver

	receiverCnt := 16
	portCnt := int(task.DstPortMax - task.DstPortMin + 1)
	if portCnt <= receiverCnt {
		receiverCnt = portCnt
	}

	portCntPerReceiver := portCnt / receiverCnt
	remainder := portCnt % receiverCnt

	targetSet := make(map[string]bool)
	for _, target := range task.DstIPs {
		targetSet[target] = true
	}

	nextPortMin := task.DstPortMin
	for i := 0; i < receiverCnt; i++ {
		dstPortMin := nextPortMin
		dstPortMax := dstPortMin + uint16(portCntPerReceiver) - 1
		if remainder > 0 {
			dstPortMax = dstPortMax + 1
			remainder = remainder - 1
		}
		task.DstPortMin = dstPortMin
		task.DstPortMax = dstPortMax
		receiver := NewUDPServerReceiver(ctx, fmt.Sprintf("%s-receiver-%d", name, i), i, task, salts, targetSet)
		receivers = append(receivers, receiver)
	}

	return &core.ReceiverGroup{Ctx: ctx, Name: name + "-receiver-group", Receivers: receivers}
}
